大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
[1, the number of unique elements in the array]
.Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
給一個nums的陣列,找出其中出現次數前k名的。
用一個count_dict來存每個數字出現的字數,最後找出dictionary中values()
最大值的index,再透過index找出對應的key值,重複這個步驟k次。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dict_s = {}
dict_t = {}
for index in range(len(s)):
if s[index] in dict_s:
dict_s[s[index]] += 1
else:
dict_s[s[index]] = 1
for index in range(len(t)):
if t[index] in dict_t:
dict_t[t[index]] += 1
else:
dict_t[t[index]] = 1
return dict_s == dict_t
今天就到這邊啦~
大家明天見